<template>
  <el-dialog :visible="visible" title="上传系统组件" width="480px" @close="onClose">
    <el-form
      ref="Form"
      v-loading="loading"
      label-width="100px"
      :show-message="false"
      :model="form"
      hide-required-asterisk
    >
      <el-form-item label="组件类型" class="mb-24" prop="groupName" required>
        <el-select v-model="form.groupName">
          <el-option v-for="(groupName, i) in groupNameList" :key="i" :value="groupName" :label="groupName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="组件名称" prop="widgetName" required>
        <el-input v-model="form.widgetName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import html2canvas from 'html2canvas';
  // import { uploadQiNiuUrl } from '@/utils';
  import { h5KeywordWidgetMap, basicKeywordWidgetMap } from './setting';
  export default {
    data() {
      return {
        visible: false,
        loading: false,
        form: {
          type: 1,
          groupName: '',
          widgetName: '',
          coverUrl: '',
          widgetJson: null
        }
      };
    },
    inject: ['isH5'],
    computed: {
      groupNameList() {
        const widgetTypeMap = new Map([
          [1, h5KeywordWidgetMap],
          [2, basicKeywordWidgetMap]
        ]);
        return Array.from(widgetTypeMap.get(this.form.type).keys());
      }
    },
    created() {
      this.$EventBus.$on('hook:UploadDialog', (widget) => {
        this.visible = true;
        widget.style.position = 'absolute';
        this.form.widgetName = widget.label;
        this.form.widgetJson = widget;
      });
    },
    destroyed() {
      this.$EventBus.$off('hook:UploadDialog');
    },
    methods: {
      onClose() {
        this.visible = false;
      },
      async onConfirm() {
        const isValid = await this.$refs['Form'].validate().catch(() => false);
        if (!isValid || this.loading) return;
        // 1. 生成组件封面
        const $widget = document.querySelector(`[data-id="${this.form.widgetJson.id}"]`);
        const $canvas = document.createElement('canvas');
        $canvas.width = $widget.offsetWidth;
        $canvas.height = $widget.offsetHeight;
        const options = {
          canvas: $canvas,
          useCORS: true,
          scale: 1
        };
        await new Promise((resolve) => {
          this.loading = true;
          setTimeout(() => resolve(), 200);
        });
        try {
          await html2canvas($widget, options);
          // const blob = await new Promise((resolve) => {
          //   $canvas.toBlob((Blob) => resolve(Blob), 'image/png');
          // });
          // const name = `widget-cover-${this.form.widgetJson.id}.png`;
          // const file = new File([blob], name, { type: blob.type });
          // this.form.coverUrl = await uploadQiNiuUrl(name, file);
        } catch (error) {
          console.warn(error);
          this.loading = false;
          return;
        }
        // 2. 上传组件
        try {
          this.form.widgetJson.label = this.form.widgetName;
          await this.$http.uploadSystemWidget({
            type: this.form.type,
            groupName: this.form.groupName,
            name: this.form.widgetName,
            url: this.form.coverUrl,
            component: JSON.stringify(this.form.widgetJson || {})
          });
          this.$message.success('上传成功');
          this.$emit('uploaded');
        } catch (error) {
          this.$message.error('上传失败');
        } finally {
          this.loading = false;
          this.onClose();
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep .el-select {
    width: 100%;
  }
</style>
